<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js异步编程之Promise错误处理</title>
  <style>
    .loading {
      display: none;
      justify-content: center;
      align-items: center;
      width: 100px;
      height: 100px;
      background-color: #9b59b6;
      color: #fff;
      border-radius: 50%;
    }
  </style>
  <script src="./ajax.js"></script>
</head>
<body>
  <ul>
    <li>Promise通过reject或throw抛出错误，或代码本身有错误都会进入错误处理回调</li>
    <li>Promise通过catch将捕获所有的错误，一般将catch放在最后，而每个Promise内部只处理成功回调，而忽略错误Promise回调</li>
    <li>Promise可自定义错误(继承Error)实现不同业务的错误处理(使用instanceof检测错误类型)</li>
    <li>Promise使用finally来处理不管是成功还是失败都会处理的逻辑(如关闭loading,释放资源等)</li>
  </ul>
  <div class="loading">加载中...</div>
  <script>
    {
      new Promise((resolve, reject) => {
        reject('fail')
        // reject(new Error('fail'))
        // throw new Error('fail')
        // a + 1
      }).then(res => {
        console.log(res)
      }, err => {
        console.log(err.message || err)
      })
    }
    {
      new Promise((resolve, reject) => {
        resolve('success')
        // reject('fail')
      }).then(res => {
        console.log(res)
        return new Promise((resolve, reject) => {
          reject(new Error('fail again...'))
        })
      }).catch(err => {
        console.log(err.message || err)
      })
    }
    {
      // 1.ParamError
      ajax('./users.json').then(res => {
        console.log(res)
      }).catch(err => {
        // 针对不同的错误做不同的处理
        if (err instanceof ParamError) {
          console.log(err.message)
        }
        if (err instanceof HttpError) {
          alert(err.message)
        }
      })
      // 2.HttpError
      ajax(`${location.href.replace('index.html', 'users.json1')}`).then(res => {
        console.log(res)
      }).catch(err => {
        // 针对不同的错误做不同的处理
        if (err instanceof ParamError) {
          console.log(err.message)
        }
        if (err instanceof HttpError) {
          alert(err.message)
        }
      })
      // 3.Request
      ajax(`${location.href.replace('index.html', 'users.json')}`).then(res => {
        console.log(res)
      }).catch(err => {
        // 针对不同的错误做不同的处理
        if (err instanceof ParamError) {
          console.log(err.message)
        }
        if (err instanceof HttpError) {
          alert(err.message)
        }
      }).finally(() => {
        const loading = document.querySelector('.loading')
        loading.style.display = 'none'
      })
    }
  </script>
</body>
</html>
